<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
App::uses('Controller', 'Controller');
App::import('Vendor', 'Facebook',array('file'=>'facebook'.DS.'facebook.php'));
/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package		app.Controller
 * @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
	public $helpers = array(
		'Facebook.Facebook',
		'Html',
		'Form',
		'Auth',
		'Session'
	 );
	public $components = array(
		'DebugKit.Toolbar',
		'RequestHandler',
		'Security',
		'Session',
		'Auth' => array(
			 'authorize' => array('Controller') // Added this line
		),
		 //'Facebook.Connect' => array('model' => 'User')
		 'Facebook.Connect'
		 // 'Twitter.Twitter'
	);


	public function __construct($request = null, $response = null) {
    	parent::__construct($request, $response);

		// Prevent the 'Undefined index: facebook_config' notice from being thrown.
		$GLOBALS['facebook_config']['debug'] = NULL;

		// // Create a Facebook client API object.
		// $this->facebook = new Facebook(null, FALSE);
	}

	public function beforeFilter() {
		// Authentication settings
		if(!empty($this->request->params['admin']))
		{
			$this->Auth->loginRedirect =  array('controller' => 'users', 'action' => 'login', 'admin' => true);
			$this->Auth->logoutRedirect =  array('controller' => 'home', 'action' => 'index','admin' => true);
		}
		else
		{
			$this->Auth->loginRedirect =  array('controller' => 'users', 'action' => 'login');
			$this->Auth->logoutRedirect =  array('controller' => 'home', 'action' => 'index','home');
		}

		$this->Auth->fields = array('username' => 'email', 'password' => 'password');
		$this->Auth->logoutRedirect = '/';
		$this->Auth->allow('index', 'view');

		$this->_checkAuth();

		//send all user info to the view

		if($this->Auth->user())
		{
			$this->set('user', $this->Auth->user());
			$this->loadModel('Profile');
			$profile = $this->Profile->find('first',array(
				'conditions' => array(
					'Profile.user_id' => $this->Auth->user('id'),
				),
				'recursive' => -1
			));

			if(!empty($profile))
			{
				$this->set('profile', $profile['Profile']);
			}
		}

		if (isset($this->params['prefix']) && $this->params['prefix'] == 'admin') {
            $this->layout = 'admin';
        } 
    }

	function _checkAuth()
	{
		$this->loadModel('User');

		if(!$this->Auth->User() && FB::getUser())
		{
		 	$fbDetail = FB::api('/me');

            //see if this facebook id is in the User database; if not, create the user using their fbid hashed as their password
            // $user_record = $this->User->find('first', array(
			                    // 'conditions' => array('or' => 
			                    	// array('facebook_id' => FB::getUser(), 'username' => $fbDetail['email'])),
			                    // 'recursive' => -1
			                // ));

			if(!empty($fbDetail))
			{
				$this->Session->Write('Facebook', $fbDetail);
			}
			// else if(!$this->Auth->User() && !empty($user_record))
			// {
				// $this->Auth->login($user_record['User']);
			// }
		}	
	}

	public function isAuthorized($user) {
		// Admin can access every action
		if (isset($user['role']) && $user['role'] === ConstUserRole::Admin) {
			return true;
		}
		// Default deny
		return false;
	}	

	public function habtmConditions($param, $model, $habtm){
        $conditions = array();
        $assocModel = $this->{$model}->hasAndBelongsToMany[$habtm];
        $assocHabtm = $this->{$model}->{$habtm}->hasAndBelongsToMany[$model];

        if(isset($param)){
            $conditions['joins'][] = array(
                'table' => $assocModel['joinTable'],
                'alias' => $assocModel['with'],
                'type' => 'inner',
                'foreignKey' => false,
                'conditions' => array(
                    "{$assocModel['with']}.{$assocModel['foreignKey']} = {$this->{$model}->alias}.{$this->{$model}->primaryKey}"
                )
            );
            $conditions['joins'][] = array(
                'table' => $this->{$model}->{$habtm}->table,
                'alias' => $habtm,
                'type' => 'inner',
                'foreignKey' => false,
                'conditions' => array(
                    "{$habtm}.{$this->{$model}->{$habtm}->primaryKey} = {$assocHabtm['with']}.{$assocHabtm['foreignKey']}",
                    "{$habtm}.name" => explode(',', $param)
                )
            );
        }
        $conditions['group'] = "{$model}.{$this->{$model}->primaryKey}";
        return $conditions;
    }

	public function beforeRender(){
		$this->_validateThis();
        parent::beforeRender();
	}

	function _validateThis() {
		$args = func_get_args();

		if (empty($args)) {
			if ($this->Session->check('Validation')) {
				$validation = $this->Session->read('Validation');
				$this->Session->delete('Validation');
				foreach ($validation as $modelName => $sessData) {
					if ($this->name != $sessData['controller']){
						if (in_array($modelName, $this->modelNames)) {
							$Model = $this->{$modelName};
						} elseif (ClassRegistry::isKeySet($modelName)) {
							$Model = ClassRegistry::getObject($modelName);
						} else {
							continue;
						}
						$Model->data = $sessData['data'];
						$Model->validationErrors = $sessData['validationErrors'];
						$this->data = Set::merge($sessData['data'],$this->data);
					}
				}
			}
		} else {
			foreach($args as $modelName) {
				if (in_array($modelName, $this->modelNames) &&
					!empty($this->{$modelName}->validationErrors)
				) {
					$this->Session->write('Validation.'.$modelName, array(
						'controller'		=>    $this->name,
						'data'				=> $this->{$modelName}->data,
						'validationErrors'  => $this->{$modelName}->validationErrors
					));
				}
			}
		}
	}

	private function __randomString($minlength = 20, $maxlength = 20, $useupper = true, $usespecial = false, $usenumbers = true){
        $charset = "abcdefghijklmnopqrstuvwxyz";
        if ($useupper) $charset .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        if ($usenumbers) $charset .= "0123456789";
        if ($usespecial) $charset .= "~@#$%^*()_+-={}|][";
        if ($minlength > $maxlength) $length = mt_rand ($maxlength, $minlength);
        else $length = mt_rand ($minlength, $maxlength);
        $key = '';
        for ($i=0; $i<$length; $i++){
            $key .= $charset[(mt_rand(0,(strlen($charset)-1)))];
        }
        return $key;
    }
}

